package com.rtech.app.service;

import java.io.File;

import org.springframework.stereotype.Service;

import com.rtech.app.constant.TraversalConstant;
import com.rtech.app.exception.SearchException;
import com.rtech.model.LoactionInfo;
 
/**
 * Implementation class for directory serach service.
 * 
 * @author ruchi.singhal
 * 
 */
@Service
public class TraversalServiceImpl implements TraversalService {

	/**
	 * Method used to fetch the information about the input file like file name,
	 * file location and permission attached with file etc.
	 * 
	 * @param filePath
	 *            - path of the file on the server for lookup
	 * @return file object with desired information to user
	 */
	public com.rtech.model.File fileSearch(String filePath) throws SearchException {
		com.rtech.model.File fileDetail = new com.rtech.model.File();
		
		String path = "";
		if(!"".equals(filePath)) {
			path = TraversalConstant.PATH_FILe_SERVER + "/" + filePath+".txt";
		}else {
			path = TraversalConstant.PATH_FILe_SERVER + "/a1.txt";
		}
		
		java.io.File f = new java.io.File(path);
		String permission = "";
		if (f.exists()) {
			fileDetail.setExist(true);
			permission += f.canRead() ? TraversalConstant.PERMISSION_READ : "";
			permission += f.canWrite() ? TraversalConstant.PERMISSION_WRITE : "";
			permission += f.canExecute() ? TraversalConstant.PERMISSION_EXECUTE	: "";
			
			System.out.println("permission - "+permission);
			permission = permission.substring(0, permission.length()-1);
			System.out.println("permission - "+permission);
			fileDetail.setPermissions(permission);
			
		} else {
			fileDetail.setExist(false);
		}
		return fileDetail;
	}

	/**
	 * Method used to fetch the complete information about the input directory.
	 * 
	 * @param dirPath
	 *            - path of directory for which user need information
	 * @return directory information
	 */
	public LoactionInfo directorySearch(String dirPath) throws SearchException {

		java.io.File f = new java.io.File(dirPath);
		traverse(f);

		return null;

		// XStream xs = new XStream();
		// xs.processAnnotations(Directory.class);
		// xs.processAnnotations(File.class);
		// xs.processAnnotations(LoactionInfo.class);
		// xs.alias("path", List.class);
		//
		// List<Book> books = (List<Book>) xs.fromXML(fakeData);

	}

	/**
	 * 
	 * @param file
	 */
	private void traverse(File file) {
		System.out.println(file);

		if (file.isDirectory()) {

			String entries[] = file.list();
			if (entries != null) {
				for (String entry : entries) {
					traverse(new File(file, entry));
				}
			}
		} else {
			// put information in file and then append into Location
			// Information.
		}
	}

}
